use std::sync::{Arc, Mutex};
use std::task::{Context, Poll,Waker};
use std::future::Future;
use std::thread;
use std::time::Duration;
use futures::executor::block_on;
pub struct TimerFuture{
    shared_state:Arc<Mutex<SharedState>>
}

struct SharedState{
    completed:bool,
    worker:Option<Waker>
}

impl Future for TimerFuture {
    type Output=();

    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut shared_state=self.shared_state.lock().unwrap();
        if shared_state.completed{
            println!("完成");
            Poll::Ready(())
        }else{
            shared_state.worker=Some(cx.waker().clone());
            println!("未完成");
            Poll::Pending
        }
    }
}

impl TimerFuture {
    pub fn new()->Self{
        let shared_state=Arc::new(Mutex::new(SharedState{
            completed:false,
            worker:None
        }));
        let shared_state_copy=shared_state.clone();
        thread::spawn(move||{
            thread::sleep(Duration::from_secs(2));
            let mut shared_state_2= shared_state_copy.lock().unwrap();
            shared_state_2.completed=true;
            //通知
            if let Some(worker)=shared_state_2.worker.take(){
                worker.wake();
            }
        });
        TimerFuture{shared_state}
    }
}

pub fn test1(){
    let future=TimerFuture::new();
    println!("实例化完成");
    // let mut shared_state= future.shared_state.lock().unwrap();
    // shared_state.worker
    block_on(future);
}